package com.jiyici.controller;

import android.app.ProgressDialog;
import android.content.Context;
import android.view.ViewGroup;

import com.jiyici.R;
import com.jiyici.network.Result;
import com.jiyici.network.WebClient;
import com.jiyici.network.WebClientFactory;
import com.jiyici.utils.NetWorkUtil;
import com.jiyici.utils.NotificationUtil;

public abstract class ServerAsyncTask extends BaseAsyncTask {

    Result result;
    ProgressDialog pd;
    protected Context context;
    boolean dialogFalg;
    private ViewGroup errorView;
    private boolean useErrorView = false;

    public ServerAsyncTask(Context context) {
        super();
        this.context = context;
    }

    public ServerAsyncTask(Context context, boolean showLoadingDialog) {
        this(context);
        showDialog(showLoadingDialog);
    }
    
    public ServerAsyncTask(Context context, ViewGroup errorView, boolean showLoadingDialog) {
        this(context);
        this.errorView = errorView;
        useErrorView = true;
        showDialog(showLoadingDialog);
    }
    
    public void start() {
        if (WebClientFactory.WebClient instanceof WebClient && !NetWorkUtil.isOnline(context)) {
            NotificationUtil.notifyError(context, R.string.error_network);
            return;
        }
        execute();
    }

    @Override
    protected void _onPreExecute() {
        if (isShowDialog()) {
            pd = new ProgressDialog(context);
            pd.setMessage(getLoadingMessage());
            pd.show();
        }
    }

    protected String getLoadingMessage() {
        return context.getString(R.string.info_loading);
    }

    public void showDialog(boolean flag) {
        dialogFalg = flag;
    }

    protected boolean isShowDialog() {
        return dialogFalg;
    }

    @Override
    protected void _doInBackground() {
        result = doRequest();
    }

    @Override
    protected void _onPostExecute() {
        if (pd != null) {
            try {
                pd.dismiss();
            } catch (Exception e) {

            }
        }
        if (result != null && result.isSuccess()) {
            onSuccess(result);
        } else {
            if (result != null) {
                CharSequence error = result.getErrorMsg(context);
                if (useErrorView) {
                    NotificationUtil.notifyError(errorView, error);
                } else {
                    NotificationUtil.notifyError(context, error);
                }
            }
        }
    }

    protected abstract Result doRequest();

    protected abstract void onSuccess(Result result);

}
